package com.dmx.cep.ws.impl;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;

import javax.jws.WebService;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.dmx.adi.AdiParseUtil;
import com.dmx.cep.entity.AdiImportTask;
import com.dmx.cep.entity.VodContentInfo;
import com.dmx.cep.exception.ObjectNotFoundException;
import com.dmx.cep.service.ContentService;
import com.dmx.cep.ws.VodService;
import com.dmx.cep.ws.datamodel.ContentStatus;
import com.dmx.cep.ws.datamodel.ReturnCode;
import com.dmx.net.ConnectionException;
import com.dmx.net.HostInfoExtractor;
import com.dmx.net.ftp.impl.FtpClient;
import com.dmx.net.ftp.impl.RemoteFtpFileNotExistsException;

@WebService(endpointInterface = "com.dmx.cep.ws.VodService")
public class VodServiceImpl implements VodService{

	Log log=LogFactory.getLog(this.getClass());
	
	private String recomm;
	
	private ContentService contentService;
	
	private String siteId;
	
//	private VodContentService  vodRSServiceProxy;
	
	public ContentService getContentService() {
		return contentService;
	}

	public void setContentService(ContentService contentService) {
		this.contentService = contentService;
	}

	@Override
	public ReturnCode assetDeleted(String[] contentIDList) {
		// TODO Auto-generated method stub
		log.info("asset delete from Third App begin...");
		
		ReturnCode returnCode=new ReturnCode();
		
		if(contentIDList==null||contentIDList.length==0){
			returnCode.setStatus(ReturnCode.STATUS_FAILURE);
			returnCode.setReason(ReturnCode.REASON_MISSING_REQUIRED_DATA_FIELD);
			log.info("missing required data.");
			return returnCode;
		}
		
		try{
			contentService.contentDelete(contentIDList);
			returnCode.setStatus(ReturnCode.STATUS_SUCCESS);
			returnCode.setReason(ReturnCode.REASON_SUCCESS);
			log.info("asset delete from Third App success.");
			return returnCode;
		}catch(ObjectNotFoundException e){
			log.error(e);
			returnCode.setStatus(ReturnCode.STATUS_FAILURE);
			returnCode.setReason(ReturnCode.REASON_RECORD_NOT_EXISTS);
			log.info("asset delete from Third App failed.");
			return returnCode;
		}catch(Exception e){
			log.error(e);
			returnCode.setStatus(ReturnCode.STATUS_FAILURE);
			returnCode.setReason(ReturnCode.REASON_INTERNAL_ERROR);
			log.info("asset delete from Third App failed.");
			return returnCode;
		}
	}

	@Override
	public ReturnCode assetUpdated(ContentStatus[] contentStatus) {
		// TODO Auto-generated method stub
		log.info("asset update from Third App begin...");
		
		ReturnCode returnCode=new ReturnCode();
		
		if(contentStatus==null||contentStatus.length==0){
			returnCode.setStatus(ReturnCode.STATUS_FAILURE);
			returnCode.setReason(ReturnCode.REASON_MISSING_REQUIRED_DATA_FIELD);
			log.info("missing required data.");
			return returnCode;
		}
		log.info("recomm is :"+recomm);
//		if(recomm!=null&&"RS2.0".equals(recomm)){
//			Vod vod=null;
//			VodContentInfo vodContentInfo =null;
//			Object obj=null;
//			for(ContentStatus cs :contentStatus){
//				try {
//					obj= contentService.getObject(VodContentInfo.class, cs.getContentId());
//					if(obj!=null){
//						vodContentInfo =(VodContentInfo)obj;
//						vod= new Vod();
//						vod.setActor(vodContentInfo.getActor());
//						vod.setBitrate(vodContentInfo.getBitrate());
//						vod.setContid(vodContentInfo.getContid());
//						vod.setCreationDate(vodContentInfo.getCreationDate());
//						vod.setDirector(vodContentInfo.getDirector());
//						vod.setExplanation(vodContentInfo.getExplanation());
//						vod.setGenre(vodContentInfo.getGenre());
//						vod.setGenre_action(vodContentInfo.getGenreAction());
//						vod.setGenre_biography(vodContentInfo.getGenreBiography());
//						vod.setGenre_children(vodContentInfo.getGenreChildren());
//						vod.setGenre_comedy(vodContentInfo.getGenreComedy());
//						vod.setGenre_detective(vodContentInfo.getGenreDetective());
//						vod.setGenre_disaster(vodContentInfo.getGenreDisaster());
//						vod.setGenre_ethics(vodContentInfo.getGenreEthics());
//						vod.setGenre_fantastic(vodContentInfo.getGenreFantastic());
//						vod.setGenre_gangster(vodContentInfo.getGenreGangster());
//						vod.setGenre_history(vodContentInfo.getGenreHistory());
//						vod.setGenre_horror(vodContentInfo.getGenreHorror());
//						vod.setGenre_legendary(vodContentInfo.getGenreLegendary());
//						vod.setGenre_lovestory(vodContentInfo.getGenreLovestory());
//						vod.setGenre_martial(vodContentInfo.getGenreMartial());
//						vod.setGenre_other(vodContentInfo.getGenreOther());
//						vod.setGenre_political(vodContentInfo.getGenrePolitical());
//						vod.setGenre_sports(vodContentInfo.getGenreSports());
//						vod.setGenre_sf(vodContentInfo.getGenreSf());
//						vod.setGenre_suspense(vodContentInfo.getGenreSuspense());
//						vod.setHdFlag(vodContentInfo.getHdFlag());
//						vod.setLanguage(vodContentInfo.getLanguage());
//						vod.setOrigin(vodContentInfo.getOrigin());
//						vod.setOriginAmerica(vodContentInfo.getOriginAmerica());
//						vod.setOriginChina(vodContentInfo.getOriginChina());
//						vod.setOriginHomgkong(vodContentInfo.getOriginHongkong());
//						vod.setOriginJapan(vodContentInfo.getOriginJapan());
//						vod.setOriginOther(vodContentInfo.getOriginOther());
//						vod.setOriginTaiwan(vodContentInfo.getOriginTaiwan());
//						vod.setProviderId(vodContentInfo.getProviderId());
//						vod.setProviderName(vodContentInfo.getProviderName());
//						vod.setRating(vodContentInfo.getRating());
//						vod.setReleaseDate(vodContentInfo.getReleaseDate());
//						vod.setRunTime(vodContentInfo.getRunTime());
//						vod.setStatus(cs.getStatus());
//						vod.setTitle(vodContentInfo.getTitle());
//						vodRSServiceProxy.addVodContent(vod);
//					}
//				} catch (SeeWProxyException e1) {
//					// TODO Auto-generated catch block
//					log.error("vod contents update for ",e1);
//				}
//			}
//		}
		
		try{
			contentService.contentUpdate(contentStatus);
			returnCode.setStatus(ReturnCode.STATUS_SUCCESS);
			returnCode.setReason(ReturnCode.REASON_SUCCESS);
			
			log.info("asset update from Third App success.");
			return returnCode;
		}catch(ObjectNotFoundException e){
			log.error(e);
			returnCode.setStatus(ReturnCode.STATUS_FAILURE);
			returnCode.setReason(ReturnCode.REASON_RECORD_NOT_EXISTS);
			
			log.info("asset update from Third App failed.");
			return returnCode;
		}catch(Exception e){
			log.error(e);
			returnCode.setStatus(ReturnCode.STATUS_FAILURE);
			returnCode.setReason(ReturnCode.REASON_INTERNAL_ERROR);
			
			log.info("asset update from Third App failed.");
			return returnCode;
		}
	}

	@Override
	public ReturnCode getTransferStatus(String providerID, String assetID) {
		// TODO Auto-generated method stub
		log.info("get transfer status [assetId="+assetID+"] begin...");
		
		ReturnCode returnCode=new ReturnCode();
		
		if(assetID==null){
			returnCode.setStatus(ReturnCode.STATUS_FAILURE);
			returnCode.setReason(ReturnCode.REASON_MISSING_REQUIRED_DATA_FIELD);
			log.info("missing required data.");
			return returnCode;
		}
		
		try{
			int status=contentService.getAssetStatus(assetID);
			switch(status){
				case 0:returnCode.setStatus(2);
				break;
				case 1:returnCode.setStatus(3);
				break;
				case 2:returnCode.setStatus(4);
				break;
				case -1:returnCode.setStatus(5);
				break;
				default:returnCode.setStatus(100);
			}
			returnCode.setReason(ReturnCode.REASON_SUCCESS);
		}catch(ObjectNotFoundException e){
			log.error(e);
			returnCode.setStatus(ReturnCode.STATUS_FAILURE);
			returnCode.setReason(ReturnCode.REASON_RECORD_NOT_EXISTS);
		}catch(Exception e){
			log.error(e);
			returnCode.setStatus(ReturnCode.STATUS_FAILURE);
			returnCode.setReason(ReturnCode.REASON_INTERNAL_ERROR);
		}
		log.info("get transfer status [assetId="+assetID+"] end.");
		return returnCode;
	}

	@Override
	public ReturnCode transferContent(String sourceUrl, String adiXmlString) {
		// TODO Auto-generated method stub
		log.info("transfer content [sourceUrl="+sourceUrl+"] from SPI begin...");
		if(sourceUrl==null||sourceUrl.trim().length()==0){
			ReturnCode returnCode=new ReturnCode(ReturnCode.STATUS_FAILURE,ReturnCode.REASON_MISSING_REQUIRED_DATA_FIELD);
			log.error("missing required data.");
			return returnCode;
		}
		
		ReturnCode returnCode=new ReturnCode();
		
		try {
			VodContentInfo contentInfo=new VodContentInfo();
			try{
				AdiParseUtil.adiValidation2(contentInfo,sourceUrl);
			}catch(Exception e){
				/*returnCode.setStatus(ReturnCode.STATUS_FAILURE);
				returnCode.setReason(ReturnCode.REASON_PARSE_ADI_ERROR);
				return returnCode;*/
				log.error(e);
			}
			
			AdiImportTask task = new AdiImportTask();
			task.setTaskName("SPI : "+contentInfo.getTitle());
			task.setAssetId(contentInfo.getContid());
			task.setFtpUrl(sourceUrl);
			task.setCreationTime(new Date());
			task.setSiteId(siteId);
			contentService.saveObject(task);
			returnCode.setStatus(ReturnCode.STATUS_SUCCESS);
			returnCode.setReason(ReturnCode.REASON_SUCCESS);
			log.info("transfer content [sourceUrl="+sourceUrl+"] from SPI end.");
		} catch (Exception e) {
			log.error(e);
			returnCode.setStatus(ReturnCode.STATUS_FAILURE);
			returnCode.setReason(ReturnCode.REASON_INTERNAL_ERROR);
			log.error("transfer content [sourceUrl="+sourceUrl+"] from SPI failed.");
		}
		return returnCode;

	}

	public String getSiteId() {
		return siteId;
	}

	public void setSiteId(String siteId) {
		this.siteId = siteId;
	}
	
	private boolean testFtpFileExists(String ftpUrl) throws Exception {
		FtpClient ftpClient = new FtpClient();
		try {
			URL url = null;
			try {
				url = new URL(ftpUrl);
			} catch (MalformedURLException exception) {
				return false;
			}

			HostInfoExtractor hostInfoExtractor = new HostInfoExtractor(url);

			hostInfoExtractor.decorateNetworkProtocolClient(ftpClient);

			try {
				ftpClient.doLogin();
			} catch (Exception e) {

			}

			if (ftpClient.isLogined() == false) {
				return false;
			}

			if (ftpClient.cdToRemoteDir(hostInfoExtractor.extractTheFolder()) == false) {
				return false;
			}
			
			ftpClient.testRemoteFileExists(hostInfoExtractor.extractFileName());


		} catch (ConnectionException ce) {
			return false;

		}  catch(RemoteFtpFileNotExistsException rfe){
			return false;
		}
		finally {
			try {
				ftpClient.close();
			} catch (Exception e) {

			}
		}
		return true;
	}



	public void setRecomm(String recomm) {
		this.recomm = recomm;
	}


	
}
